const currencyEl1 = <HTMLSelectElement>document.getElementById('currency1')
const amountEl1 = <HTMLInputElement>document.getElementById('amount1')
const currencyEl2 = <HTMLSelectElement>document.getElementById('currency2')
const amountEl2 = <HTMLInputElement>document.getElementById('amount2')

const swapBtn = <HTMLButtonElement>document.getElementById('swap')
const rateEl = <HTMLDivElement>document.getElementById('rate')

// Fetch exchange rate and update the DOM
function caclulate() {
  const currency1 = currencyEl1.value
  const currency2 = currencyEl2.value

  fetch(`https://api.exchangerate-api.com/v4/latest/${currency1}`)
    .then((res) => res.json())
    .then((data) => {
      const rate = data.rates[currency2]
      rateEl.innerText = `1 ${currency1} = ${rate} ${currency2}`
      amountEl2.value = (Number(amountEl1.value) * rate).toFixed(2)
    })
}

// Add event listener
currencyEl1.addEventListener('change', caclulate)
amountEl1.addEventListener('change', caclulate)
currencyEl2.addEventListener('change', caclulate)
amountEl2.addEventListener('change', caclulate)
swapBtn.addEventListener('click', () => {
  const tmp = currencyEl1.value
  currencyEl1.value = currencyEl2.value
  currencyEl2.value = tmp
  caclulate()
})

caclulate()
